import json

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from goods.models import SKU
from meiduo_mall.utils.cookiesecret import CookieSecret


class CartsView(View):

    # 添加购物车
    def post(self, request):
        # 1、提取参数
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        count = data.get('count')
        selected = data.get('selected', True)  # 默认勾选

        # 2、校验参数
        if not all([sku_id, count]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必要字段'})

        try:
            sku = SKU.objects.get(pk=sku_id)
        except SKU.DoesNotExist as e:
            return JsonResponse({'code': 400, 'errmsg': 'sku不存在'})

        # 3、业务数据处理
        user = request.user
        if user.is_authenticated:
            # 3.1、登陆 —— 存入redis
            conn = get_redis_connection('carts')  # 5号
            # (1)、存哈希对象 —— 商品和数量
            # 如果当前sku_id在哈希对象里面，需要把count累加
            # conn.hmset('carts_%s'%user.id, {sku_id:count})
            conn.hincrby('carts_%s' % user.id, sku_id, count)  # 如果sku_id存在则累加，不存在则新增
            # (2)、存集合 —— 记录选中状态
            if selected:
                conn.sadd('selected_%s' % user.id, sku_id)
            else:
                conn.srem('selected_%s' % user.id, sku_id)
            return JsonResponse({'code': 0, 'errmsg': 'ok'})
        else:
            # 3.2、未登陆 —— 存入cookie
            # (1)、当前请求cookie里面是否已经有购物车数据了
            cookie_str = request.COOKIES.get('carts')  # carts是存入cookie的购物车数据的key
            if cookie_str:
                # cookie有购物车数据，需要解密得到购物车字典数据
                cart_dict = CookieSecret.loads(cookie_str)
            else:
                # cookie中没有购物车数据
                cart_dict = {}

            # (2)、追加当前新增的商品
            if sku_id in cart_dict:
                # 把数量累
                cart_dict[sku_id]['count'] += count
                cart_dict[sku_id]['selected'] = selected
            else:
                cart_dict[sku_id] = {
                    'count': count,
                    'selected': selected
                }

            # 把最新的cookie 购物车字典数据
            cookie_str = CookieSecret.dumps(cart_dict)
            response = JsonResponse({
                'code': 0,
                'errmsg': 'ok'
            })
            response.set_cookie('carts', cookie_str, max_age=14 * 3600 * 24)
            return response

    # 查询购物车，展示购物车
    def get(self, request):
        # 后续为了方便业务数据组织，从redis或者cookie读取的购物车数据，统一组成字典数据
        cart_dict = {}
        user = request.user
        if user.is_authenticated:
            conn = get_redis_connection('carts')
            # (1)、读取购物车商品数量，哈希数据
            # redis_carts = {b'1': b'5', b'2': b'3'}
            redis_carts = conn.hgetall('carts_%s' % user.id)
            # (2)、购物车选中状态，集合数据
            # redis_selected = [b'1', b'2']
            redis_selected = conn.smembers('selected_%s' % user.id)
            sku_ids = redis_carts.keys()
            for sku_id in sku_ids:
                cart_dict[int(sku_id)] = {
                    'count': int(redis_carts[sku_id]),
                    'selected': sku_id in redis_selected
                }
        else:
            cookie_str = request.COOKIES.get('carts')
            if cookie_str:
                cart_dict = CookieSecret.loads(cookie_str)
            else:
                cart_dict = {}
        # 读取mysql获取sku商品的详细信息，组织响应参数
        sku_ids = cart_dict.keys()
        cart_skus = []

        for sku_id in sku_ids:
            sku = SKU.objects.get(pk=sku_id)
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price,
                'count': cart_dict[sku_id]['count'],
                'selected': cart_dict[sku_id]['selected']
            })
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'cart_skus': cart_skus
        })

    # 更新购物车
    def put(self, request):
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        count = data.get('count')
        selected = data.get('selected', True)

        if not all([sku_id, count]):
            return JsonResponse({
                'code': 400,
                'errmsg': '缺少参数'
            })
        try:
            sku = SKU.objects.get(pk=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({
                'code': 400,
                'errmsg': '商品不存在'
            })

        user = request.user
        if user.is_authenticated:
            # 登录状态
            conn = get_redis_connection('carts')
            # 修改商品数量 -- 哈希对象，设置键值对默认覆盖原值
            conn.hset('carts_%s' % user.id, sku_id, count)
            # 修改选中状态
            if selected:
                conn.sadd('selected_%s' % user.id, sku_id)
            else:
                conn.srem('selected_%s' % user.id, sku_id)

            update_dict = {
                    'id': sku.id,
                    'count': count,
                    'selected': selected
            }
            return JsonResponse({
                'code': 0,
                'errmsg': 'ok',
                'cart_sku': update_dict
            })
        else:
            cookie_str = request.COOKIES.get('carts')
            if cookie_str:
                cart_dict = CookieSecret.loads(cookie_str)
            else:
                cart_dict = {}
            if sku_id in cart_dict:
                cart_dict[sku_id]['count'] = count
                cart_dict[sku_id]['selected'] = selected

            cookie_str = CookieSecret.dumps(cart_dict)
            response = JsonResponse({
                'code': 0,
                'errmsg': 'ok'
            })
            response.set_cookie('carts', cookie_str)
            return response

    # 删除购物车
    def delete(self, request):
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        print(sku_id)

        # 校验参数
        if not sku_id:
            return JsonResponse({
                'code': 400,
                'errmsg': '缺少参数'
            })
        try:
            sku = SKU.objects.get(pk=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({
                'code': 400,
                'errmsg': '商品不存在'
            })

        # 数据处理
        user = request.user
        if user.is_authenticated:
            # 登录，删除redis购物车指定商品sku数据
            conn = get_redis_connection('carts')
            # 从哈希对象中删除
            conn.hdel('carts_%s' % user.id, sku_id)
            # 把sku_id从集合中删除
            conn.srem('selected_%s' % user.id, sku_id)
            return JsonResponse({
                'code': 0,
                'errmsg': 'ok'
            })
        else:
            # 未登录，删除购物车数据
            cookie_str = request.COOKIES.get('carts')
            if cookie_str:
                cart_dict = CookieSecret.loads(cookie_str)
            else:
                cart_dict = {}

            if sku_id in cart_dict:
                # 删除键值对
                cart_dict.pop(sku_id)
            # 重新加密在cookie中
            cookie_str = CookieSecret.dumps(cart_dict)
            response = JsonResponse({
                'code': 0,
                'errmsg': 'ok'
            })
            response.set_cookie('carts', cookie_str)
            return response


class CartsSelectAllView(View):
    def put(self, request):
        data = json.loads(request.body.decode())
        selected = data.get('selected')  # 没有传递参数就是None

        # 判读selected 类型，必须是bool类型
        if not isinstance(selected, bool):
            return JsonResponse({
                'code': 400,
                'errmsg': '参数有误'
            })

        # 数据处理
        user = request.user

        if user.is_authenticated:
            # 登录状态，全部选中购物车
            conn = get_redis_connection('carts')
            # 获取所有sku商品
            # redis_carts = {b'1':b'5', b'2': b'6'}
            redis_carts = conn.hgetall('carts_%s' % user.id)
            # 把所有sku的商品的id加入集合
            sku_ids = redis_carts.keys()  # [b'1', b'2']
            if selected:
                conn.sadd('selected_%s' % user.id, *sku_ids)
            else:
                conn.srem('selected_%s' % user.id, *sku_ids)
                return JsonResponse({
                    'code': 0,
                    'errmsg': 'ok'
                })
        else:
            # 未登录，全选购物车数据
            cookie_str = request.COOKIES.get('carts')
            if cookie_str:
                cart_dict = CookieSecret.loads(cookie_str)
            else:
                cart_dict = {}
            # 把购物车字典中所有对商品的selected设置为True
            sku_ids = cart_dict.keys()
            for sku_id in sku_ids:
                cart_dict[sku_id]['selected'] = selected  # 前端传来的selected是True表示全选，为False表示全部取消
            # 加密薪字典写入cookie
            cookie_str = CookieSecret.dumps(cart_dict)
            response = JsonResponse({
                'code': 0,
                'errmsg': 'ok'
            })
            response.set_cookie('carts', cookie_str)
            return response


# 展示商品页面简单购物车展示商品页面简单购物车
class CartsSimpleView(View):
    def get(self, request):
        # 判断用户是否一登录
        user = request.user
        if user.is_authenticated:
            # 用户一登录，查询购物车数据
            client = get_redis_connection('carts')
            carts_data = client.hgetall(user.id)
            carts_dict = {
                int(key.decode()): json.loads(value.decode()) for key, value in carts_data.items()
            }
        else:
            # 用户未登录,查询购物车
            carts_str = request.COOKIES.get('carts')
            if carts_str:
                carts_dict = CookieSecret.loads(carts_str)
            else:
                carts_dict = {}

        # 构造JSON数据
        cart_skus = []
        sku_ids = carts_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': carts_dict.get(sku.id)['count'],
                'default_image_url': sku.default_image.url
            })

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'cart_skus': cart_skus
        })
